// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <pollux/core/plan_node.h>
#include <pollux/exec/operator.h>
#include <pollux/exec/operator_trace_reader.h>

namespace kumo::pollux::exec::trace {
    /// This is a scan operator for query replay. It uses traced data from a
    /// specific directory path, which is
    /// $traceRoot/$taskId/$nodeId/$pipelineId/$driverId.
    ///
    /// A plan node can be split into multiple pipelines, and each pipeline can be
    /// divided into multiple operators. Each operator corresponds to a driver,
    /// which is a thread of execution. Pipeline IDs and driver IDs are sequential
    /// numbers starting from zero.
    ///
    /// For a single plan node, there can be multiple traced data files. To find the
    /// right input data file for replaying, we need to use both the pipeline ID and
    /// driver ID.
    ///
    /// The trace data directory up to the $nodeId, which is $root/$taskId/$nodeId.
    /// It can be found from the QueryReplayScanNode. However the pipeline ID and
    /// driver ID are only known during operator creation, so we need to figure out
    /// the input traced data file and the output type dynamically.
    class OperatorTraceScan final : public SourceOperator {
    public:
        OperatorTraceScan(
            int32_t operatorId,
            DriverCtx *driverCtx,
            const std::shared_ptr<const core::TraceScanNode> &traceScanNode);

        RowVectorPtr getOutput() override;

        BlockingReason isBlocked(ContinueFuture * /* unused */) override {
            return BlockingReason::kNotBlocked;
        }

        bool isFinished() override;

    private:
        std::unique_ptr<OperatorTraceInputReader> traceReader_;
        bool finished_{false};
    };
} // namespace kumo::pollux::exec::trace
